package com.java.second_goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.second_goods.common.utils.DateUtils;
import com.java.second_goods.common.utils.StringUtils;
import com.java.second_goods.entity.Booking;
import com.java.second_goods.entity.Goods;
import com.java.second_goods.mapper.BookingMapper;
import com.java.second_goods.mapper.GoodsMapper;
import com.java.second_goods.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单 服务层实现
 */
@Service
public class BookingServiceImpl extends ServiceImpl<BookingMapper, Booking> implements BookingService {

    @Autowired
    private BookingMapper bookingMapper;

    @Autowired
    private GoodsMapper goodsMapper;
    /**
     * 查询订单信息
     *
     * @param id 订单ID
     * @return 订单信息
     */
    @Override
    public Booking selectBookingById(String id) {
        return bookingMapper.selectById(id);
    }

    /**
     * 查询订单列表
     *
     * @param booking 订单信息
     * @return 订单集合
     */
    @Override
    public List<Booking> selectBookingList(Booking booking) {
        LambdaQueryWrapper<Booking> queryWrapper = new LambdaQueryWrapper<>();
        if (booking != null) {
            // 构建查询条件
            if (booking.getUserId() != null) {
                queryWrapper.eq(Booking::getUserId, booking.getUserId());
            }
            if (booking.getGoodsId() != null) {
                queryWrapper.eq(Booking::getGoodsId, booking.getGoodsId());
            }
            if (StringUtils.isNotEmpty(booking.getStatus())) {
                queryWrapper.eq(Booking::getStatus, booking.getStatus());
            }
            if (booking.getBookingDate() != null) {
                queryWrapper.eq(Booking::getBookingDate, booking.getBookingDate());
            }
            if (booking.getHasReviewed() != null) {
                queryWrapper.eq(Booking::getHasReviewed, booking.getHasReviewed());
            }
        }
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(Booking::getCreateTime);
        return bookingMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID查询订单列表
     *
     * @param userId 用户ID
     * @return 订单集合
     */
    @Override
    public List<Booking> selectBookingsByUserId(Integer userId) {
        return bookingMapper.selectBookingsByUserId(userId);
    }

    /**
     * 根据厨师ID查询订单列表
     *
     * @param chefId 厨师ID
     * @return 订单集合
     */
    @Override
    public List<Booking> selectBookingsByChefId(Integer chefId) {
        return bookingMapper.selectBookingsByChefId(chefId);
    }

    /**
     * 根据状态查询订单列表
     *
     * @param status 状态
     * @return 订单集合
     */
    @Override
    public List<Booking> selectBookingsByStatus(String status) {
        return bookingMapper.selectBookingsByStatus(status);
    }

    /**
     * 新增订单
     *
     * @param booking 订单信息
     * @return 结果
     */
    @Override
    public int insertBooking(Booking booking) {
        // 设置默认订单ID
        if (StringUtils.isEmpty(booking.getId())) {
            booking.setId(generateOrderId());
        }

        // 设置默认状态
        if (StringUtils.isEmpty(booking.getStatus())) {
            booking.setStatus("pending");
        }

        // 设置默认评价状态
        if (booking.getHasReviewed() == null) {
            booking.setHasReviewed(false);
        }

        return bookingMapper.insert(booking);
    }

    /**
     * 修改订单
     *
     * @param booking 订单信息
     * @return 结果
     */
    @Override
    public int updateBooking(Booking booking) {
        return bookingMapper.updateById(booking);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单ID
     * @return 结果
     */
    @Override
    public int deleteBookingById(String id) {
        return bookingMapper.deleteById(id);
    }

    /**
     * 批量删除订单信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBookingByIds(String[] ids) {
        return bookingMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 更新订单状态
     *
     * @param bookingId 订单ID
     * @param status 状态
     * @return 结果
     */
    @Override
    public int updateBookingStatus(String bookingId, String status) {
        return bookingMapper.updateBookingStatus(bookingId, status);
    }

    /**
     * 取消订单
     *
     * @param bookingId 订单ID
     * @return 结果
     */
    @Override
    public int cancelBooking(String bookingId) {
        return bookingMapper.cancelBooking(bookingId, new Date());
    }

    /**
     * 检查是否有重复预约
     *
     * @param chefId 厨师ID
     * @param bookingDate 预约日期
     * @param bookingTime 预约时间
     * @return 是否有重复预约
     */
    @Override
    public boolean checkDuplicateBooking(Integer chefId, Date bookingDate, Date bookingTime) {
        return bookingMapper.checkDuplicateBooking(chefId, bookingDate, bookingTime);
    }

    /**
     * 创建订单
     *
     * @param booking 订单信息
     * @return 订单信息
     */
    @Override
    @Transactional
    public Booking createBooking(Booking booking) {
        // 检查是否有重复预约
        if (checkDuplicateBooking(booking.getGoodsId(), booking.getBookingDate(), booking.getBookingTime())) {
            return null;
        }

        // 设置订单ID
        booking.setId(generateOrderId());

        // 设置状态
        booking.setStatus("pending");
        System.out.println("booking"+" "+ booking.getGoodsId());
        // 设置是否评价
        booking.setHasReviewed(false);
        Goods goods = goodsMapper.selectById(booking.getGoodsId());
        System.out.println("goods: " + goods);
        if (goods == null) {
            System.out.println("Cannot find goods with ID: " + booking.getGoodsId());
            return null;
        }
        BigDecimal totalAmount = goods.getPrice();
        // 订单总金额

        if (booking.getDiscount() != null) {
            totalAmount = totalAmount.subtract(booking.getDiscount());
        }
        booking.setTotalAmount(totalAmount);

        // 保存订单
        bookingMapper.insert(booking);

        return booking;
    }

    /**
     * 生成订单号
     */
    private String generateOrderId() {
        return DateUtils.dateTimeNow("yyyyMMdd") + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
    }
}